﻿package net.wangit.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.dom4j.Document;

public class FTPUtil {

	private FTPUtil() {
	}

	public static boolean downLoad(String urlString, String filePath) {
		return false;
	}

	public static boolean upLoad(String urlString, String filePath) {
		if (Checker.isEmpty(urlString) || Checker.isEmpty(filePath))
			return false;
		try {
			URL url = new URL(urlString);
			URLConnection uc = url.openConnection();
			OutputStream os = uc.getOutputStream();
			File file = new File(filePath);
			if (file.exists()) {
				FileInputStream is = new FileInputStream(filePath);
				byte temp[] = new byte[4096];
				int i;
				while ((i = is.read(temp)) != -1)
					os.write(temp, 0, i);
				is.close();
			}
			os.close();
		} catch (Exception ex) {
			System.out.println("Ftp upLoad failed!");
			ex.printStackTrace();
			return false;
		}
		return true;
	}

	private static boolean uploadXML(String urlString, Document doc) {
		try {
			URL url = new URL(urlString);
			URLConnection uc = url.openConnection();
			OutputStream os = uc.getOutputStream();
			InputStream is = new ByteArrayInputStream(doc.asXML().getBytes(
					"utf-8"));
			byte temp[] = new byte[4096];
			int i;
			while ((i = is.read(temp)) != -1)
				os.write(temp, 0, i);
			is.close();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static void main(String args[]) {
		Document doc = null;
		String urlString = "ftp://username:password@111.111.111.111/temp.xml";
		boolean result = uploadXML(urlString, doc);
		System.out.println("upload is " + (result ? "successfully" : "failed"));
	}
}
